<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button-group>
        <goBack></goBack>
        <el-button type="primary" @click="bghandleGenerate">生成报告</el-button>
        <el-button type="primary" @click="handleAdd">
          点击重新上传
        </el-button>
      </el-button-group>
      <el-table :data="baogaoList" stripe style="width: 100%" highlight-current-row>
        <el-table-column type="index" min-width="100">
        </el-table-column>
        <el-table-column prop="name" label="文件名">
          <template slot-scope="scope">
            <div class="firedownload" @click="fileDownload(scope.row)">{{scope.row.name}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="上传时间">

        </el-table-column>
      </el-table>
    </el-col>
    <el-col :span="24">
      <el-card class="box-card">
        <div slot="header" class="clearfix subtab_tit">
          <span>数据信息</span>
        </div>
        <Chart v-for="(item,index) in echartsOption" :id="getEchartID(index)" :echartOption="item" :key="getEchartID(index)"></Chart>
      </el-card>

    </el-col>
    <el-card class="box-card">
      <div slot="header" class="clearfix subtab_tit">
        <span>数据完善</span>
      </div>
      <span v-show="!AnalysisFormShow" @click="handleEditAnalysisForm">{{AnalysisForm }}</span>
      <textarea class="analysistext" v-focus="analysisFormFocus" @blur="bghandle(AnalysisFormShow)" v-show="AnalysisFormShow" v-model="AnalysisForm" />
    </el-card>
    <el-col :span="24">
      <el-card class="box-card">
        <div slot="header" class="clearfix subtab_tit">
          <span>历史上传记录</span>
        </div>
        <el-table :data="historyList" stripe style="width: 100%" highlight-current-row>
          <el-table-column type="index" min-width="100">
          </el-table-column>
          <el-table-column prop="name" label="文件名">
            <template slot-scope="scope">
              <div class="firedownload" @click="fileDownload(scope.row)">{{scope.row.name}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="time" label="上传时间">
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="130">
            <template slot-scope="scope">
              <el-button @click.native.prevent="handleDel(scope.$index, scope.row)" icon="el-icon-delete" size="small" type="danger"> </el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-card>
    </el-col>

    <!-- 文件上传 -->
    <el-dialog title="文件上传" :visible.sync="isUploadShow" :close-on-click-modal="false">
      <div class="inner">
        <el-upload ref="elupload" class="upload" drag :action="importFileUrl" :data="upLoadData" :limit="1" :headers="httpHeaders" :auto-upload="false" :beforeUpload="beforeAvatarUpload" :onSuccess="uploadSuccess">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            <el-button @click="uploadAction" slot="tip" type="primary">上传</el-button>
            <p>只能上传txt/word/excel文件</p>
          </div>
        </el-upload>
      </div>
    </el-dialog>

    <!-- 数据完善弹框 -->
    <!-- <el-dialog title="数据完善" :visible.sync="AnalysisFormShow" :close-on-click-modal="false">
      <el-form label-width="150px" :rules="AnalysisFormRules" :model="AnalysisForm" ref="AnalysisForm">
        <el-form-item label="分析测点" prop="number">
          <el-select v-model="AnalysisForm.number" placeholder="请选择分析测点">
            <el-option v-for="item in sensorTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启动次数" prop="time">
          <el-input-number v-model="AnalysisForm.time" :step="1"></el-input-number> 次
        </el-form-item>
        <el-form-item label="平均启动分钟数" prop="minutes">
          <el-input-number v-model="AnalysisForm.minutes" :step="0.1"></el-input-number> 分钟
        </el-form-item>
        <el-form-item label="制冷周期" prop="cycle">
          <el-input-number v-model="AnalysisForm.cycle" :step="0.1"></el-input-number> 分钟
        </el-form-item>
        <el-form-item label="降温幅度" prop="amplitude">
          <el-input-number v-model="AnalysisForm.amplitude" :step="0.1"></el-input-number> ℃
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="AnalysisFormShow = false">取消</el-button>
        <el-button type="primary" @click.native="bghandleGenerate">生成报告</el-button>
      </div>
    </el-dialog> -->
  </section>
</template>
<script>
import NProgress from "nprogress";
import { getToken } from "@/utils/auth";
import goBack from "@/components/public/goback";
import Chart from "@/components/public/Chart";
import focus from "@/directives/focus/index.js";
export default {
  directives: {
    focus
  },
  components: {
    goBack,
    Chart
  },
  data() {
    return {
      analysisFormFocus: false,
      sensorarr: [],
      sensorList: [],
      sensorTypes: [],
      baogaoList: [],
      historyList: [],
      isUploadShow: false,
      AnalysisFormShow: false,
      httpHeaders: {
        Authorization: getToken()
      },
      importFileUrl: "/files/upload",
      upLoadData: {
        projectid: this.$route.params.projectid,
        type: 3
      },
      option: {
        title: {
          text: "温湿度图表",
          x: "center",
          top: 10
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            animation: false
          }
        },

        xAxis: {
          //X轴
          type: "category",
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            rotate: 10
          },
          data: []
        },
        yAxis: [
          {
            type: "value",
            scale: true,
            axisLabel: {
              formatter: "{value} °C"
            },
            splitLine: {
              show: false
            }
          }
        ],
        series: [], // 数据
        legend: {
          //图例
          top: "bottom",
          itemGap: 5,
          itemWidth: 15,
          itemHeight: 10,
          data: []
        },
        color: "#0569d0"
      },
      seriesFormat: {
        name: "",
        type: "line",
        smooth: true,
        data: []
      },
      echartsOption: [],
      AnalysisForm: "",
      AnalysisLoading: false,
      AnalysisFormRules: {
        number: [
          {
            required: true,
            message: "请选择分析测点",
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    handleEditAnalysisForm() {
      this.AnalysisFormShow = true;
      let that = this;
      setTimeout(() => {
        that.analysisFormFocus = true;
      }, 10);
    },

    getEchartID(index) {
      return "echarts_" + index;
    },
    // 生成时等待
    Loading() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.3)"
      });
      setTimeout(() => {
        loading.close();
      }, 9500);
    },
    bghandle() {
      this.AnalysisFormShow = this.analysisFormFocus = false;
      let params = {
        projectid: this.$route.params.projectid,
        conclusion: this.AnalysisForm
      };
      this.axios.post("/projects/yanzhengxinxi/update", params).then(reply => {
        this.editLoading = false;
        NProgress.done();
        if (reply.data.status === 0) {
          this.$notify({
            title: "成功",
            message: "提交成功",
            type: "success"
          });
        } else {
          this.$message({
            message: `提交失败，错误码${reply.data.status},请联系管理员`,
            type: "warning"
          });
        }
      });
    },
    // 生成报告
    bghandleGenerate() {
      this.$confirm("确认生成word文档吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.Loading();
        this.listLoading = true;
        NProgress.start();
        let params = {
          projectid: this.$route.params.projectid
        };
        Object.assign(params, this.AnalysisForm);

        this.axios.post("/analysis/start", params).then(reply => {
          this.listLoading = false;
          NProgress.done();
          if (reply.data.status === 0) {
            this.$confirm("生成成功! 确定现在下载？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                window.open("/uploads/" + reply.data.data + ".docx");
                this.$message({
                  type: "success",
                  message: "下载成功!"
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消下载"
                });
              });
          } else {
            this.$message({
              message: `生成失败，错误码${reply.data.status},请联系管理员`,
              type: "warning"
            });
          }
        });
      });
    },
    uploadAction() {
      this.$confirm("确认提交吗？", "提示", {})
        .then(() => {
          this.$refs.elupload.submit();
        })
        .catch(e => {});
    },
    //文件下载
    fileDownload(row) {
      window.open("/" + row.dir);
    },

    //验证报告历史列表
    getbaogaoList() {
      this.listLoading = true;
      NProgress.start();
      this.axios
        .get("/projects/" + this.$route.params.projectid, {
          params: {}
        })
        .then(reply => {
          this.listLoading = false;
          NProgress.done();
          if (reply.data.status === 0) {
            if (reply.data.data.baogaofileObject != null) {
              let baogaofileJSON = reply.data.data.baogaofileObject;
              this.baogaoList = [];
              this.baogaoList.push(baogaofileJSON.file);
              this.historyList = baogaofileJSON.list;
            }
          } else {
            this.$message({
              message: `查询验证报告出错，错误码${
                reply.data.status
              },请联系管理员`,
              type: "warning"
            });
          }
        });
      this.axios
        .get("/projects/yanzhengxinxi/" + this.$route.params.projectid)
        .then(reply => {
          this.listLoading = false;
          NProgress.done();
          if (reply.data.status === 0) {
            let informationFormfile = reply.data.data;
            this.AnalysisForm =
              informationFormfile.conclusion == ""
                ? "通过对出风口  号点的数据分析，制冷机在6小时内共启动  次，平均  分钟启动一次，低于每小时启动次数应小于5次的规定；制冷周期为  分钟，降温幅度  ℃，说明制冷机的性能较好。"
                : informationFormfile.conclusion;
          }
        });
    },
    //删除
    handleDel: function(index, row) {
      this.$confirm("确认删除该历史文件吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.listLoading = true;
        NProgress.start();
        let params = {
          projectid: this.$route.params.projectid,
          uuid: row.uuid
        };
        this.axios.post("/files/delete", params).then(reply => {
          this.listLoading = false;
          NProgress.done();
          if (reply.data.status === 0) {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success"
            });
            this.getbaogaoList();
          } else {
            this.$message({
              message: `删除失败，错误码${reply.data.status},请联系管理员`,
              type: "warning"
            });
          }
        });
      });
    },
    //上传对话框显示
    handleAdd() {
      this.isUploadShow = true;
    },
    //文件检查
    beforeAvatarUpload(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const extension3 = file.name.split(".")[1] === "doc";
      const extension4 = file.name.split(".")[1] === "docx";
      const extension5 = file.name.split(".")[1] === "txt";
      if (
        !extension &&
        !extension2 &&
        !extension3 &&
        !extension4 &&
        !extension5
      ) {
        this.$message({
          message: "上传模板只能是 xls、xlsx、doc、docx、txt 格式!",
          type: "warning"
        });
      }
      return extension || extension2 || extension3 || extension4 || extension5;
    },

    uploadSuccess(response, file, fileList) {
      this.uploading = false;
      if (response.status == 0) {
        this.$refs.elupload.clearFiles();
        this.isUploadShow = false;
        this.getbaogaoList();
        this.$notify({
          type: "success",
          message: "文件上传成功",
          offset: 40
        });
      } else {
        return this.$message({ type: "error", message: "上传失败" });
      }
    },
    getEchartsList() {
      this.axios
        .get("/projects/dianweituxinxi/" + this.$route.params.projectid)
        .then(reply => {
          if (reply.data.status === 0) {
            reply.data.data.map(child => {
              if (child.sensorlocation == 2) {
                this.sensorarr.push(child.sensorcode);
                this.sensorarr.forEach((child, i) => {
                  this.sensorList.push({
                    label: `${child}号传感器`,
                    value: i
                  });
                });
                let kv = {};
                this.sensorTypes = this.sensorList.filter(sensor => {
                  if (!kv[sensor.label + "," + sensor.value]) {
                    kv[sensor.label + "," + sensor.value] = true;
                    return sensor;
                  }
                });
                console.log(this.sensorTypes);
              }
            });
            // 获取具体数值
            this.axios
              .get(
                "/analysis/origindata?projectid=" + this.$route.params.projectid
              )
              .then(reply => {
                if (reply.data.status === 0) {
                  let wentaiOptions = JSON.parse(JSON.stringify(this.option));
                  var wentaiCanvasDataObject = {};
                  var wentaiStart, wentaiEnd;

                  reply.data.data.forEach(child => {
                    // 稳态
                    if (child.verifytype == 4) {
                      wentaiStart = child.operdate.substring(5, 16);
                      wentaiEnd = child.operdate.substring(5, 16);
                      if (
                        wentaiCanvasDataObject[child.sensorcode] == undefined
                      ) {
                        wentaiCanvasDataObject[child.sensorcode] = {
                          temperature: [],
                          time: []
                        };
                      }
                      wentaiCanvasDataObject[child.sensorcode][
                        "temperature"
                      ].push(child.temperature);
                      wentaiCanvasDataObject[child.sensorcode]["time"].push(
                        child.operdate.substring(5, 16)
                      );
                    }
                  });
                  for (var index in wentaiCanvasDataObject) {
                    const result = this.sensorarr.findIndex(
                      item => item == index
                    );
                    if (result < 0) {
                      continue;
                    }
                    var optionsSingle = JSON.parse(JSON.stringify(this.option));
                    var seriesFormatSingle = JSON.parse(
                      JSON.stringify(this.seriesFormat)
                    );
                    optionsSingle.xAxis.data =
                      wentaiCanvasDataObject[index].time;
                    seriesFormatSingle.name = index + "#";
                    seriesFormatSingle.data =
                      wentaiCanvasDataObject[index].temperature;
                    optionsSingle.title.text = index + "#稳态阶段温度曲线图";
                    optionsSingle.series.push(seriesFormatSingle);
                    optionsSingle.legend.data.push(index + "#");
                    this.echartsOption.push(optionsSingle);
                  }
                } else {
                  this.$message({
                    message: `获取数据失败，错误码${
                      reply.data.status
                    },请联系管理员`,
                    type: "warning"
                  });
                }
              });
          } else {
            this.$message({
              message: `获取位置失败，错误码${reply.data.status},请联系管理员`,
              type: "warning"
            });
          }
        });
    }
  },
  mounted() {
    this.getbaogaoList();
    this.getEchartsList();
  }
};
</script>
 <style lang="scss" scoped>
.subtable thead {
  color: #909399;
  font-weight: 500;
}
.subtable td,
.subtable th .is-leaf {
  border-bottom: 1px solid #ebeef5;
}
.subtable th {
  padding: 12px 0;
  min-width: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
}
.cell a {
  text-decoration: none;
  color: #409eff;
}
.box-card {
  margin-bottom: 25px;
}
.analysistext {
  display: block;
  resize: vertical;
  padding: 5px 15px;
  line-height: 1.5;
  box-sizing: border-box;
  width: 100%;
  font-size: inherit;
  color: #606266;
  background-color: #fff;
  background-image: none;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  min-height: 33px;
  margin-top: 0px;
  margin-bottom: 0px;
  height: 50px;
  font-size: 14px;
  font-family: "微软雅黑";
}
</style>

